package level.state;

import image.ImageUtility;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Line2D;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.imageio.ImageIO;

import core.Constants;

import level.editor.tool.layer.Visibility;

public class StatePainter
{
	public static void paintGrid(Graphics2D g, int width, int height)
	{
		g.setColor(Color.GRAY);
		for (int i = (int) Constants.TILE_SIZE; i <= width; i += Constants.TILE_SIZE)
		{
			g.draw(new Line2D.Float((float) i, 0f, (float) i, (float) height));
		}
		for (int i = (int) Constants.TILE_SIZE; i <= height; i += Constants.TILE_SIZE)
		{
			g.draw(new Line2D.Float(0f, (float) i, (float) width, (float) i));
		}
	}

	public static void paintState(State state, Graphics2D g,
			HashMap<String, Image> images, Visibility vis)
	{
		// Set visibility parameters here

		for (int i : vis.getZOrders())
		{
			StateLayer layer = StateHandler.getLayer(state, i);
			paintLayer(g, layer, images);
		}
	}

	private static void paintLayer(Graphics2D g, StateLayer layer,
			HashMap<String, Image> images)
	{
		if (layer instanceof StateTileLayer)
			paintTileLayer(g, (StateTileLayer) layer, images);
	}

	private static void paintTileLayer(Graphics2D g, StateTileLayer layer,
			HashMap<String, Image> images)
	{
		if (layer.getTiles().size() != 0)
		{
			for (Tile tile : layer.getTiles())
			{
				UpdateImage(images, tile.getIconPath());
				g.drawImage(
						ImageUtility.makeColorTransparent(images.get(tile
								.getIconPath()), new Color(255, 0, 255)), tile
								.getX(), tile.getY(),
						tile.getX() + tile.getW(), tile.getY() + tile.getH(),
						tile.getSx(), tile.getSy(),
						tile.getSx() + tile.getSw(),
						tile.getSy() + tile.getSh(), null);
			}
		}
	}

	private static void UpdateImage(HashMap<String, Image> images,
			String imagePath)
	{
		if (!images.containsKey(imagePath))
		{
			try
			{
				images.put(imagePath, ImageIO.read(new File(imagePath)));
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
}
